<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" style="padding-right: 5px;">
      <el-row>
        <el-col :span="8">
          <el-form-item label="年份" prop="yearSign" style="width: 100%;">
            <el-select v-model="queryParams.yearSign" placeholder="请选择年份">
                <el-option
                  v-for="dict in yearOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <!--<el-col :span="8" style="padding-left: 12px; padding-right: 12px;">
          <el-form-item label="月份" prop="month" style="width: 100%;">
            <el-select v-model="queryParams.month" placeholder="请选择月份" clearable>
                <el-option
                  v-for="dict in monthOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>-->
        <el-col :span="8" style="padding-left: 12px;">
          <el-form-item label="申报对象" prop="nickName" style="width: 100%;">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入申报对象"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="组织" prop="deptId" style="width: 100%;">
            <el-tree-select
              v-model="queryParams.deptId"
              :data="deptOptions"
              :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
              value-key="deptId"
              placeholder="请选择组织"
              check-strictly
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8" style="margin: 15px 0px;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="Download"
          @click="handleExport"
          v-hasPermi="['partybuilding:WorkScore:export']"
        >导出</el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['partybuilding:WorkScore:import']"
        >批量导入</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
            icon="UserFilled"
            @click="handleAudit"
            v-hasPermi="['partybuilding:WorkScore:approve']"
        >积分审批</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" @handleQuery="handleQuery" @resetQuery="resetQuery"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="WorkScoreList" @selection-change="handleSelectionChange">
      <el-table-column type="index" label="排名" align="center" width="90"></el-table-column>
      <el-table-column label="姓名" align="left" prop="nickName" />
      <el-table-column label="组织名称" align="left" prop="deptName" />
      <el-table-column label="积分" align="left" prop="scoreSum" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="danger" @click="handleApply(scope.row)" v-hasPermi="['partybuilding:WorkScore:applyForAdding']">积分申报</el-button>
          <el-divider direction="vertical" />
          <el-button link type="danger" @click="handleDetail(scope.row)" v-hasPermi="['partybuilding:WorkScore:query']">积分明细</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改党员积分对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="WorkScoreRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="党员名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入党员名称" />
        </el-form-item>
        <el-form-item label="部门id" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入部门id" />
        </el-form-item>
        <el-form-item label="组织名称" prop="orgName">
          <el-input v-model="form.orgName" placeholder="请输入组织名称" />
        </el-form-item>
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="积分类型" prop="typeId">
          <el-input v-model="form.typeId" placeholder="请输入积分类型" />
        </el-form-item>
        <el-form-item label="积分题目" prop="title">
          <el-input v-model="form.title" placeholder="请输入积分题目" />
        </el-form-item>
        <el-form-item label="题目id" prop="titleId">
          <el-input v-model="form.titleId" placeholder="请输入题目id" />
        </el-form-item>
        <el-form-item label="周期值，月 200012 ,季度 210004,半年 220002,年 302024" prop="cycle">
          <el-input v-model="form.cycle" placeholder="请输入周期值，月 200012 ,季度 210004,半年 220002,年 302024" />
        </el-form-item>
        <el-form-item label="原始积分" prop="scoreOrigin">
          <el-input v-model="form.scoreOrigin" placeholder="请输入原始积分" />
        </el-form-item>
        <el-form-item label="申请积分" prop="addScore">
          <el-input v-model="form.addScore" placeholder="请输入申请积分" />
        </el-form-item>
        <el-form-item label="原因" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入原因" />
        </el-form-item>
        <el-form-item label="审批备注" prop="approvalRemark">
          <el-input v-model="form.approvalRemark" placeholder="请输入审批备注" />
        </el-form-item>
        <el-form-item label="审批记录[{时间，人员，结果,备注}]" prop="approvalRecord">
          <el-input v-model="form.approvalRecord" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 积分明细 -->
    <apply-score ref="applyScoreRef"/>

    <!-- 积分明细 -->
    <score-detail ref="detailScoreRef"/>

    <!-- 积分审批 -->
    <audit-score ref="auditScoreRef"/>
  </div>
</template>

<script setup name="WorkScore">
import { listOrg } from "@/api/partybuilding/Org";
import { listWorkScore, getWorkScore, delWorkScore, addWorkScore, updateWorkScore } from "@/api/partybuilding/WorkScore";
import ApplyScore from './component/ApplyScore.vue'
import ScoreDetail from './component/ScoreDetail.vue'
import AuditScore from './component/AuditScore.vue'

const { proxy } = getCurrentInstance();

const WorkScoreList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref(undefined);
const yearOptions = ref([]);
const monthOptions = ref([]);
const openApply = ref(false);
const openDetail = ref(false);
const applyScoreRef = ref(null);
const detailScoreRef = ref(null);
const auditScoreRef = ref(null);
  
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    userName: null,
    deptId: null,
    orgName: null,
    type: 0,
    typeName: null,
    typeId: null,
    title: null,
    titleId: null,
    cycle: null,
    scoreOrigin: null,
    addScore: null,
    approvalStatus: null,
    approvalRemark: null,
    approvalRecord: null
  },
  rules: {
    type: [
      { required: true, message: "0党员积分，1组织积分不能为空", trigger: "change" }
    ],
    titleId: [
      { required: true, message: "题目id不能为空", trigger: "blur" }
    ],
    addScore: [
      { required: true, message: "申请积分不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);


function handleApply(row) {
  openApply.value = true;
  applyScoreRef.value.refresh(row.deptId, queryParams.value.yearSign, 0, row.scoreSum, row.deptName, row.userId, row.nickName);
}

function handleDetail(row) {
  openDetail.value = true;
  detailScoreRef.value.refresh(row.userId, queryParams.value.yearSign, 0, row.scoreSum);
}

function handleAudit() {
  auditScoreRef.value.refresh(null, queryParams.value.yearSign, 0);
}

/** 查询党员积分列表 */
function getList() {
  loading.value = true;
  if (queryParams.value.yearSign == null || queryParams.value.yearSign == "") {
    queryParams.value.yearSign = new Date().getFullYear();
  }
  listWorkScore(queryParams.value).then(response => {
    WorkScoreList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    userName: null,
    deptId: null,
    orgName: null,
    type: null,
    typeName: null,
    typeId: null,
    title: null,
    titleId: null,
    cycle: null,
    scoreOrigin: null,
    addScore: null,
    remark: null,
    createTime: null,
    approvalStatus: null,
    approvalRemark: null,
    approvalRecord: null
  };
  proxy.resetForm("WorkScoreRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


function getYearMonthOptions() {
  const now = new Date();
  const curYear = now.getFullYear();
  yearOptions.value = [];
  monthOptions.value = [];
  for (let i = curYear; i > curYear - 5; i--) {
    yearOptions.value.push({ value: i, label: i + "年" });
  }
  monthOptions.value.push({ value: 0, label: "全部" });
  for (let i = 1; i <= 12; i++) {
    monthOptions.value.push({ value: i, label: i + "月" });
  }
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  listOrg().then(response => {
    deptOptions.value = proxy.handleTree(response.rows, "deptId");
  });
};

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加党员积分";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getWorkScore(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改党员积分";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["WorkScoreRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateWorkScore(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addWorkScore(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除党员积分编号为"' + _ids + '"的数据项？').then(function() {
    return delWorkScore(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('partybuilding/WorkScore/export', {
    ...queryParams.value
  }, `WorkScore_${new Date().getTime()}.xlsx`)
}

getYearMonthOptions();
getDeptTree();
getList();
</script>